package top.oauth2.sms.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.oauth2.common.response.ResponseMessage;

import java.util.List;

/**
 * @author xphu
 * @version 1.0
 * @date 2021/9/16 14:39
 */
@Slf4j
@RestControllerAdvice
public class BadRequestExceptionHandler extends Exception{

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity validationBodyException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p ->{
                FieldError fieldError = (FieldError) p;
                log.error("Data check failure : object{"+fieldError.getObjectName()+"},field{"+fieldError.getField()+
                        "},errorMessage{"+fieldError.getDefaultMessage()+"}");
            });

        }
        return ResponseEntity.ok(ResponseMessage.builder().error("目录名称不符合标准").message());
    }

}
